package com.sangmo.fts.process.inventory.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.fts.basic.model.FileUpload;
import com.sangmo.fts.basic.service.FileUploadService;
import com.sangmo.fts.process.inventory.interfaces.IfContractDocumentRequest;
import com.sangmo.fts.process.inventory.model.IfContract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class IfContractDocumentService {

    @Autowired
    private IfContractEntityService ifContractEntityService;

    @Autowired
    private FileUploadService fileUploadService;

    public FileUpload createPledgorDoc(Long contractId, Long fileUploadId) {
        IfContract contract = ifContractEntityService.get(contractId);
        if (contract.isPledgorConfirm()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.ifContract.upload.permit.disabled");
        }
        contract.setPledgorDoc(fileUploadId);
        ifContractEntityService.save(contract);
        return create(contractId, fileUploadId, "IfContract.Pledgor");
    }

    public FileUpload createPledgeeDoc(Long contractId, Long fileUploadId) {
        IfContract contract = ifContractEntityService.get(contractId);
        if (contract.isPledgeeConfirm()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.ifContract.upload.permit.disabled");
        }
        contract.setPledgeeDoc(fileUploadId);
        ifContractEntityService.save(contract);
        return create(contractId, fileUploadId, "IfContract.Pledgee");
    }

    public FileUpload createRegulatorDoc(Long contractId, Long fileUploadId) {
        IfContract contract = ifContractEntityService.get(contractId);
        if (contract.isRegulatorConfirm()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.ifContract.upload.permit.disabled");
        }
        contract.setRegulatorDoc(fileUploadId);
        ifContractEntityService.save(contract);
        return create(contractId, fileUploadId, "IfContract.Regulator");
    }

    public FileUpload create(Long contractId, Long fileUploadId, String refType) {
        FileUpload upload = fileUploadService.updateRef(fileUploadId, ""+contractId, refType);
        return upload;
    }
}
